<template>
  <div>
    <el-upload
      class="avatar-uploader"
      list-type="picture-card"
      action="#"
      :file-list="fileList"
      :class="{display:fileList.length>0}"
      :on-preview="preview"
      :on-remove="remove"
      :on-change="change"
      :http-request="upload"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showPercent" style="width: 147px" :percentage="percent" :show-text="false" />
    <el-dialog title="预览" :visible="outerVisible" @close="outerVisible=false">
      <center><img style="width:60%" :src="urlImg" alt=""></center>
    </el-dialog>
  </div>
</template>

<script>
// 引入库
import COS from 'cos-js-sdk-v5'
// 创建实例
const cos = new COS({
  SecretId: 'AKIDZ0EEFIKEuOdkphNdfU7MjiWCi16xa3av',
  SecretKey: 'C9HJGED0ZzCC5JZTAcqqcAUlRnwrXCQl'
})
export default {
  components: {},
  props: {},
  data() {
    return {
      showPercent: false,
      percent: 0,
      outerVisible: false,
      urlImg: '',
      fileList: []
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    preview(img) {
      this.urlImg = img.url
      this.outerVisible = true
    },
    remove(file, fileList) {
      console.log(file)
      console.log(55, fileList)
      // 删除数组url
      this.fileList = [...fileList]
    },
    change(file, fileList) {
      console.log(file)
      console.log(61, fileList)
      // 新增数组url
      this.fileList = [...fileList]
    },
    beforeUpload(file) { // 上传图片前的钩子
      const maxsize = 200 * 1024
      if (maxsize < file.size) {
        this.$message.error('文件大小超过200K')
        return false
      }
      const whiteList = ['image/jpeg', 'image/png']
      if (whiteList.indexOf(file.type) === -1) {
        this.$message.warning('目前只支持 Jpeg Png 的格式')
        return false
      }
    },
    upload(data) {
      this.showPercent = true
      cos.putObject({
        Bucket: 'hr65-1307117923', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: data.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(89, JSON.stringify(progressData))

          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        this.fileList[0].url = `http://${data.Location}`
        this.fileList[0].status = `success`
        this.showPercent = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
.display {
  ::v-deep .el-upload--picture-card {
    display: none;
  }
}
</style>
